package com.demo.hystrix.controller;

import com.demo.hystrix.client.SearchApiService;
import com.demo.hystrix.util.HystrixPropertiesManager;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * Author by admin, Email xx@xx.com, Date on 2020/6/2.
 * PS: Not easy to write code, please indicate.
 * HystrixProperty的name属性值在HystrixPropertiesManager这个类中
 */
@DefaultProperties(defaultFallback = "GlobalExecption")
@RestController
public class testhystrix {
    @Autowired
    SearchApiService searchApiService;

    @GetMapping("test/{id}")
    @HystrixCommand(fallbackMethod = "Execptiontest",commandProperties = {
            //执行隔离线程超时（毫秒)
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS,value = "5000"),
            //启用断路器
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED,value = "true" ),
            //断路器要求的请求次数阈值
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value = "10"),
            //毫秒故障中的断路器休眠窗口
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,value = "10000"),
            //失败率多少跳闸
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,value = "60")})
    public Result test(@PathVariable("id")Integer id ){
        if (1== id){
            int a=1/0;
        }
        Result result = searchApiService.queryAllQuestion();
        return  new Result(true, StatusCode.OK,"正常查询",result);

    }
    //出现异常走hystrix
    public Result Execptiontest(@PathVariable("id")Integer id){
//        Result result = searchApiService.queryAllQuestion();
        return new Result(true, StatusCode.OK,"出现异常");
    }
    @HystrixCommand
    @GetMapping("test3")
    public Result test3(){
//        int a=1/0;
        try {
            //睡3秒
            TimeUnit.MICROSECONDS.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Result result = searchApiService.queryAllQuestion();
        return new Result(true, StatusCode.OK,"出现异常",result);
    }

    public Result GlobalExecption(){
        return new Result(true, StatusCode.OK,"我是全局默认异常程序出现异常，稍后再试！！！！");
    }


}
